package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
@Autowired
    private UserMapper userMapper;
@Autowired
private OrdersMapper ordersMapper;

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = this.getDateList(begin, end);
        Map params = new HashMap();
        params.put("beginDate", begin);
        params.put("endDate", end);
        List<Map> userMapList = this.userMapper.groupCountUserByParams(params);
        //分组查询每日新增用户数
        Map<String, Long> userMap = userMapList.stream().collect(Collectors.toMap(u -> (String) u.get("date"), u -> (Long) u.get("num")));
        //查询截止到开始日期之前的用户总数
        params.put("date", begin.minusDays(1));
        params.put("newUserflag", false);
        Integer beginUserCount = this.userMapper.countUserByParams(params);
        List<Integer> totalUserList = new ArrayList<>();
        List<Long> newUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //当天新增用户数
            Long newUserCount = userMap.get(date.toString());
            newUserCount = newUserCount == null ? 0 : newUserCount;
            newUserList.add(newUserCount);
            //截至当天用户总数
            beginUserCount += newUserCount.intValue();
            totalUserList.add(beginUserCount);
        }
        //3、组装UserReportVO并返回
        return UserReportVO.builder().dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();

    }

    /**
 * 根据起始日期，得到区间内的所有日期
 * @param begin 开始日期
 * @param end 结束日期
 * @return 区间内的所有日期
 */
private List<LocalDate> getDateList(LocalDate begin,LocalDate end){
    List<LocalDate> dateList = new ArrayList<>();
    dateList.add(begin);
    while (!begin.isEqual(end)){
        begin = begin.plusDays(1);
        dateList.add(begin);
    }
    return  dateList;
}

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //1、根据起始日期，得到区间内的所有日期
        List<LocalDate> dateList = this.getDateList(begin,end);
        //2、查询每日的营业额，得到一个营业额List(分组统计营业额)
        Map paramMap = new HashMap();
        paramMap.put("beginDate",begin);
        paramMap.put("endDate",end);
        paramMap.put("status", Orders.COMPLETED);
        //分组查询
        //    select DATE_FORMAT(order_time,'%Y-%m-%d') as `date`,sum(amount) amount from orders where status = 5
        //    and DATE_FORMAT(order_time,'%Y-%m-%d') >= '2023-04-22'
        //    and DATE_FORMAT(order_time,'%Y-%m-%d') <= '2023-04-28'
        //    group by `date`
        List<Map> turnoverMapList = this.ordersMapper.groupSumAmountByParams(paramMap);
        //将结果集转换成Map，方便后续根据日期取营业额
        Map<String, BigDecimal> turnoverMap = turnoverMapList.stream().collect(Collectors.toMap(m -> (String) m.get("date"), m -> (BigDecimal) m.get("amount")));
        List<BigDecimal> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            BigDecimal amount = turnoverMap.get(date.toString());
            amount = ObjectUtils.isEmpty(amount) ? BigDecimal.valueOf(0.0) : amount;
            turnoverList.add(amount);
        }
        //3、将list转成逗号拼接的字符串
        String dateListStr = StringUtils.join(dateList, ",");
        dateListStr = dateList.stream().map(date -> date.toString()).collect(Collectors.joining(","));

        //4、组装TurnoverReportVO并返回
        String turnoverListStr = StringUtils.join(turnoverList, ",");
        return TurnoverReportVO.builder().dateList(dateListStr).turnoverList(turnoverListStr).build();

    }
    }